package com.beaven.imclient.widget;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.PopupWindow;
import com.beaven.imclient.R;

/**
 * created by beaven on 2017/5/5 11:44.
 * <p>
 * 底部弹出的pop视图
 */

public class DeviceBottomPopup extends PopupWindow {

  public DeviceBottomPopup(final Activity activity, View view, View parent, Drawable bgDrawable,
      int width, int height) {
    // 设置视图
    this.setContentView(view);
    // 设置弹出窗体可点击
    this.setFocusable(true);

    setWidth(width);
    setHeight(height);

    setBackgroundDrawable(bgDrawable);

    // 设置弹出窗体显示时的动画，从底部向上弹出
    this.setAnimationStyle(R.style.popup_bottom_anim);
    //设置PopupWindow显示位置（从底部弹出）
    showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

    setWindowAlpha(activity, true);
    //设置PopupWindow关闭监听，当PopupWindow关闭，背景恢复1f
    setOnDismissListener(new OnDismissListener() {
      @Override public void onDismiss() {
        setWindowAlpha(activity, false);
      }
    });
  }

  public void setWindowAlpha(Activity activity, boolean isOpen) {
    final Window window = activity.getWindow();
    final WindowManager.LayoutParams lp = window.getAttributes();
    window.setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND,
        WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    ValueAnimator animator;
    if (isOpen) {
      animator = ValueAnimator.ofFloat(1.0f, 0.5f);
    } else {
      animator = ValueAnimator.ofFloat(0.5f, 1.0f);
    }
    animator.setDuration(400);
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
      @Override public void onAnimationUpdate(ValueAnimator animation) {
        lp.alpha = (float) animation.getAnimatedValue();
        window.setAttributes(lp);
      }
    });
    animator.start();
  }
}
